package cn.workreport.modules.mail.util;

import cn.StoreApplication;
import cn.workreport.modules.mail.enums.MIMEEnum;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.InputStreamSource;

import javax.activation.DataSource;
import java.io.*;
import java.util.HashMap;

/**
 * 描述【邮件转换类】
 *
 * @author lihuanyao
 * @date 2022/4/26 9:53
 */
public class MailUtil {

    private static Configuration configuration;
    private static ClassLoader loader;

    // 指定模板存放文件夹
    private static final String BASE_PACKAGE_PATH = "mail-templates";

    /**
     * 转换输入类
     *
     * @param in
     * @return
     */
    public static InputStreamSource InputStreamToInputStreamSource(InputStream in) {
        ByteArrayOutputStream baos = null;
        InputStreamSource inputStreamSource = null;
        BufferedInputStream bis = new BufferedInputStream(in);
        try {
            baos = new ByteArrayOutputStream();// 创建一个ByteArray输出流
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = bis.read(buffer, 0, 8192)) != -1) {
                baos.write(buffer, 0, bytesRead);
            }
            inputStreamSource = new ByteArrayResource(baos.toByteArray());//创建ByteArrayResource用ByteArray输出流的字节数组
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (baos != null) {
                try {
                    baos.close();//关闭BufferedOutputStream输出流
                } catch (Exception e) {

                }
            }
            if (bis != null) {
                try {
                    bis.close();//关闭ByteArray输出流
                } catch (Exception e) {

                }
            }
        }
        return inputStreamSource;
    }

    /**
     * 输入流转文件
     *
     * @param ins
     * @param file
     */
    public static void inputstreamtofile(InputStream ins, File file) {
        OutputStream os = null;
        try {
            os = new FileOutputStream(file);
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                }
            }
            try {
                ins.close();
            } catch (IOException e) {
            }
        }
    }

    /**
     * 创建 DataSource 类型
     *
     * @param inputStream
     * @param mimeEnum    mime协议类型
     * @param name
     * @return
     */
    public static DataSource createDataSource(InputStream inputStream, MIMEEnum mimeEnum, String name) {
        return createDataSource(inputStream, mimeEnum.getCode(), name);
    }

    /**
     * 创建 DataSource 类型
     *
     * @param inputStream 输入流
     * @param contentType mime协议类型
     * @param name        文件名
     * @return
     */
    public static DataSource createDataSource(InputStream inputStream, String contentType, String name) {
        return new DataSource() {
            @Override
            public InputStream getInputStream() throws IOException {
                return inputStream;
            }

            @Override
            public OutputStream getOutputStream() {
                throw new UnsupportedOperationException("Read-only javax.activation.DataSource");
            }

            @Override
            public String getContentType() {
                return contentType;
            }

            @Override
            public String getName() {
                return name;
            }
        };
    }

    /**
     * 初始化模板配置
     */
    private static void initTemplate() {
        if (configuration == null) {
            synchronized (MailUtil.class) {
                if (configuration == null) {
                    //构建 Freemarker 的基本配置
                    configuration = new Configuration(Configuration.VERSION_2_3_0);
                    // 配置模板位置，启动类的位置StoreApplication
                    loader = StoreApplication.class.getClassLoader();
                    configuration.setClassLoaderForTemplateLoading(loader, BASE_PACKAGE_PATH);
                }
            }
        }
    }

    /**
     * 依赖 Freemarker 实现
     *
     * @param obj          必须为健值对格式 支持实体类
     * @param templateName 模板名称
     * @return
     */
    public static String ObjectToTemplate(Object obj, String templateName) {
        String text = "";
        // 初始化模板
        if (configuration == null) {
            initTemplate();
        }
        //加载模板
        Template template = null;
        StringWriter out = new StringWriter();
        try {
            template = configuration.getTemplate(templateName);
            //模板渲染，渲染的结果将被保存到 out 中 ，将out 中的 html 字符串发送即可
            template.process(obj, out);
            text = out.toString();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                out.close();
            } catch (IOException e) {
            }
        }
        return text;
    }


    public static void main(String[] args) throws Exception {
//        File file = new File("D:\\tools\\Unicode_jb51\\jb51.net.txt");
//        InputStream in = new FileInputStream(file);
//        InputStreamSource inputStreamSource = MailUtil.InputStreamToInputStreamSource(in);
//        File file1 = new File("D:\\tools\\Unicode_jb51\\jb51.net1.txt");
//        inputstreamtofile(inputStreamSource.getInputStream(),file1);
        HashMap<String, Object> map = new HashMap<>();
        map.put("username", "李四");
        map.put("num", "132");
        map.put("salary", "120000");
        System.out.println(ObjectToTemplate(map, "DayReport.ftl"));
    }
}
